package service

import (
	"context"
	"github.com/google/uuid"
	"go.uber.org/zap"
	"golang-sgg-daijia/api/v1"
	"golang-sgg-daijia/internal/repository/tencentcloud"
	"mime/multipart"
	"strings"
)

type CosService interface {
	UploadFile(ctx context.Context, file *multipart.FileHeader, path string) (*v1.CosUploadVo, error)
}

func NewCosService(
	service *Service,
	cosClient tencentcloud.CosClient,
) CosService {
	return &cosService{
		Service:   service,
		cosClient: cosClient,
	}
}

type cosService struct {
	*Service
	cosClient tencentcloud.CosClient
}

func (c *cosService) UploadFile(ctx context.Context, file *multipart.FileHeader, path string) (*v1.CosUploadVo, error) {
	fileType := file.Filename[strings.LastIndex(file.Filename, "."):]
	// 文件重命名
	// 01.jpg
	// /driver/auth/0o98754.jpg
	uploadPath := "/driver/" + path + "/" + strings.ReplaceAll(uuid.New().String(), "-", "") + fileType
	f, err := file.Open()
	if err != nil {
		c.logger.WithContext(ctx).Error("cosService|UploadFile|Open", zap.Any("data", map[string]interface{}{
			"uploadPath": uploadPath,
		}), zap.Error(err))
		return nil, err
	}
	// 向桶中保存文件
	err = c.cosClient.Put(ctx, uploadPath, f, nil)
	if err != nil {
		return nil, err
	}

	// 图片审核
	isPass, err := c.cosClient.ImageAudit(ctx, uploadPath)
	if err != nil {
		return nil, err
	}
	if !isPass {
		// 删除违规图片
		return nil, v1.ErrImageAuditFail
	}


	// 回显Url
	showUrl, err := c.cosClient.GetImageUrl(ctx, uploadPath)
	if err != nil {
		return nil, err
	}
	return &v1.CosUploadVo{
		Url:     uploadPath,
		ShowUrl: showUrl,
	}, nil
}
